var express = require('express')
var router = express.Router()
var FoodsDal = require('../../../common/food').FoodsDal
var foodsDal = new FoodsDal()
var fs = require('fs')

router.get('/', (req, res) => {
    var page = ''
    var filter = {}
    console.log(req.query)
    if (req.query.page) {
        page = Number(req.query.page)
    }
    if (req.query.type) {
        filter.type = req.query.type
    }
    foodsDal.getDataByPage(page, filter, data => {
        res.json({ status: "y", msg: "获取分页数据成功", data: data })
    })
})

//查询
router.get('/:id', (req, res) => {
    foodsDal.findByID(req.params.id, data => {
        res.json({ status: 'y', msg: '获取数据成功', data: data })
    })
})
//新增
router.post('/create', (req, res) => {
    foodsDal.save(req.body, isOK => {
        if (isOK) {
            res.json({ status: 'y', msg: '新增记录成功' })
        } else {
            res.json({ status: 'n', msg: '新增记录失败,未知错误' })
        }
    })
})
//修改
router.post('/update/:id', (req, res) => {
    if (req.body.img != req.query.img) {
        var imgUrl = 'public' + req.query.img
        fs.unlink(imgUrl, function (err) {
            if (err) {
                console.log('删除失败')
            } else {
                console.log('删除成功')
            }
        })
    } 
    foodsDal.updateByID(req.params.id, req.body, isOK => {
        if (isOK) {
            res.json({ status: 'y', msg: '修改记录成功' })
        } else {
            res.json({ status: 'n', msg: '修改记录失败,未知错误' })
        }
    })
})
//删除
router.post('/delete/:id', (req, res) => {
    var imgUrl = 'public' + req.query.img
    fs.unlink(imgUrl, function (err) {
        if (err) {
            console.log('删除失败')
        } else {
            console.log('删除成功')
        }
    })
    foodsDal.del(req.params.id, isOK => {
        if (isOK) {
            res.json({ status: 'y', msg: '删除记录成功' })
        } else {
            res.json({ status: 'n', msg: '删除记录失败,未知错误' })
        }
    })
})
module.exports = router